import { _decorator, Component, Node, Prefab, ScrollView, instantiate, UITransform } from 'cc';
import { UIBase } from "../../../[框架]/通用UI/UIBase";
import TaskProxy from "../Controller/TaskProxy";
import { TaskDefine } from "../Model/TaskDefine";
import TaskCell from "./TaskCell";
import { UIManager } from '../../../[框架]/通用UI/UIManager';
import TaskResMgr from '../Model/TaskResMgr';
import { Toast } from '../../../[框架]/通用UI/Toast/Toast';

const { ccclass, property } = _decorator;

@ccclass('TaskView')
export default class TaskView extends UIBase {



    @property(Prefab)
    private cell: Prefab = null;

    private scrollView: ScrollView = null;

    @property(Node)
    private btnClose: Node = null;

    private spaceingY: number = 15;
    private cellHeight: number = 120;

    private nodePool: Node[] = [];
    private readonly POOL_INIT_SIZE: number = 6;

    private static instance: any = null;

    public static showWnd() {
        if (!TaskResMgr.ready) {
            Toast.show("资源加载中,稍后再试");
            return;
        }
        this.instance = this.instance || instantiate(TaskResMgr.taskViewPrefab) as any as Node;
        if (!this.instance.active) {
            this.instance.active = true;
        }
        UIManager.instance.addChildTo(this.instance as any, "normal");
    }

    onEnable() {

        // this.zoom();
        UIManager.instance.adjustUILayer();
        this.btnClose.on(Node.EventType.TOUCH_END, this.hide, this);
        this.scrollView = this.node.getComponentInChildren(ScrollView);
        Guyu.dispatcher.on(TaskDefine.Events.Task_Update, this, this.updateTask);
        this.initNodePool();
        this.updateTask();
        this.showAD();
    }

    private showAD() {
        if (!Guyu.RuntimeSDK.onMiniGame) {
            return;
        }
        let config = TaskProxy.inst.taskConfig;
        let ad插屏 = Guyu.AdFactory.getInterstitialAd({ adUnitId: TaskProxy.inst.taskConfig.inset_adunits });
        ad插屏.show();
        // let adCustom = Guyu.AdFactory.getCustomAd({
        //     adUnitId: config.banner_adunits
        // });
        // let windowInfo = Guyu.AdapterManager.adapter.windowInfo;
        // let top = windowInfo.screenHeight - 126;

        // adCustom.show({
        //     left: 0,
        //     top: top,
        // });
    }

    private hideAD() {
        if (!Guyu.RuntimeSDK.onMiniGame) {
            return;
        }
        let config = TaskProxy.inst.taskConfig;
        // let adCustom = Guyu.AdFactory.getCustomAd({
        //     adUnitId: config.banner_adunits
        // });
        // adCustom.hide();
        // let ad插屏 = Guyu.AdFactory.getInterstitialAd({ adUnitId: TaskProxy.inst.taskConfig.inset_adunits });
        // ad插屏.hide();
    }


    protected onDestroy(): void {
        TaskView.instance = null;
        Guyu.dispatcher.off(TaskDefine.Events.Task_Update, this, this.updateTask);
    }
    private initNodePool() {
        for (let i = 0; i < this.POOL_INIT_SIZE; i++) {
            const node = instantiate(this.cell);
            this.nodePool.push(node);
        }
    }

    private getNodeFromPool(): Node {
        return this.nodePool.length > 0 ? this.nodePool.pop() : instantiate(this.cell);
    }

    private recycleNode(node: Node) {
        if (node && node.parent) {
            node.parent = null;
            this.nodePool.push(node);
        }
    }

    private updateTask() {
        let content = this.scrollView.content;
        let taskList = TaskProxy.inst.taskConfig.reward_task;

        // 回收所有现有节点
        const existingNodes = [...content.children];
        existingNodes.forEach(node => this.recycleNode(node));

        for (let i = 0; i < taskList.length; i++) {
            let taskVO = taskList[i];
            let cell = this.getNodeFromPool();
            cell.name = `[Task]-${taskVO.ad_task_name}_${i + 1}`;
            cell.setPosition(0, -i * (this.cellHeight + this.spaceingY));
            content.addChild(cell);
            cell.getComponent(TaskCell)?.updateUI(taskVO);
        }

        const totalTasks = taskList.length;
        const totalHeight = this.cellHeight * totalTasks + this.spaceingY * (totalTasks - 1);
        content.getComponent(UITransform).setContentSize(content.getComponent(UITransform).contentSize.width, totalHeight);
        this.scrollView.scrollToTop();
    }

    onDisable() {
        super.onDisable?.();
        // 清理对象池
        this.nodePool.length = 0;
        this.hideAD();
    }
}
